package handler

import (
	"context"
	"errors"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"

	proto "mxshop_srvs/goods_srv/proto/gen/v1"
)

func (s *Service) CreateBanner(_ context.Context, req *proto.BannerRequest) (*proto.BannerResponse, error) {
	bannerID, err := s.DB.CreateBanner(req)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}
	return &proto.BannerResponse{Id: bannerID}, nil
}

func (s *Service) BannerList(_ context.Context, _ *emptypb.Empty) (*proto.BannerListResponse, error) {
	banners, total, err := s.DB.GetBannerList()
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}

	var bannerResp []*proto.BannerResponse
	for _, banner := range banners {
		bannerResp = append(bannerResp, &proto.BannerResponse{
			Id:    banner.ID,
			Index: banner.Index,
			Image: banner.Image,
			Url:   banner.Url,
		})
	}

	return &proto.BannerListResponse{
		Total: total,
		Data:  bannerResp,
	}, nil
}

func (s *Service) UpdateBanner(_ context.Context, req *proto.BannerRequest) (*emptypb.Empty, error) {
	banner, err := s.DB.GetBanner(req.Id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, status.Error(codes.NotFound, "")
		}
		return nil, status.Error(codes.Internal, "")
	}

	_, rows, err := s.DB.UpdateBanner(banner, req)
	if err != nil || rows == 0 {
		return nil, status.Error(codes.Internal, "")
	}
	return &emptypb.Empty{}, nil
}

func (s *Service) DeleteBanner(_ context.Context, req *proto.BannerRequest) (*emptypb.Empty, error) {
	row, err := s.DB.DeleteBanner(req)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}
	if row == 0 {
		return nil, status.Error(codes.NotFound, "")
	}
	return &emptypb.Empty{}, nil
}
